/*
 * lws-minimal-secure-streams-mqtt
 *
 * Written in 2021 by Andy Green <andy@warmcat.com>
 *
 * This file is made available under the Creative Commons CC0 1.0
 * Universal Public Domain Dedication.
 *
 *
 * This demonstrates a minimal mqtt client using secure streams api.
 *
 * It connects test.mosquitto.org and exchange MQTT messages.
 *
 */

#include <libwebsockets.h>
#include <string.h>
#include <signal.h>

#define TEST_CLIENT_ID "SN12345678"

static int interrupted, bad = 1, test_nontls;
static lws_state_notify_link_t nl;

#if !defined(LWS_SS_USE_SSPC)
static const char * const default_ss_policy =
	"{"
	  "\"release\":"			"\"01234567\","
	  "\"product\":"			"\"myproduct\","
	  "\"schema-version\":"			"1,"
	  "\"retry\": ["	/* named backoff / retry strategies */
		"{\"default\": {"
			"\"backoff\": ["	 "1000,"
						 "2000,"
						 "3000,"
						 "5000,"
						"10000"
				"],"
			"\"conceal\":"		"5,"
			"\"jitterpc\":"		"20,"
			"\"svalidping\":"	"300,"
			"\"svalidhup\":"	"310"
		"}}"
	  "],"
	  "\"certs\": [" /* named individual certificates in BASE64 DER */
		"{\"test_mosq_org\": \""
		"MIIEAzCCAuugAwIBAgIUBY1hlCGvdj4NhBXkZ/uLUZNILAwwDQYJKoZIhvcNAQEL"
		"BQAwgZAxCzAJBgNVBAYTAkdCMRcwFQYDVQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwG"
		"A1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1vc3F1aXR0bzELMAkGA1UECwwCQ0ExFjAU"
		"BgNVBAMMDW1vc3F1aXR0by5vcmcxHzAdBgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hv"
		"by5vcmcwHhcNMjAwNjA5MTEwNjM5WhcNMzAwNjA3MTEwNjM5WjCBkDELMAkGA1UE"
		"BhMCR0IxFzAVBgNVBAgMDlVuaXRlZCBLaW5nZG9tMQ4wDAYDVQQHDAVEZXJieTES"
		"MBAGA1UECgwJTW9zcXVpdHRvMQswCQYDVQQLDAJDQTEWMBQGA1UEAwwNbW9zcXVp"
		"dHRvLm9yZzEfMB0GCSqGSIb3DQEJARYQcm9nZXJAYXRjaG9vLm9yZzCCASIwDQYJ"
		"KoZIhvcNAQEBBQADggEPADCCAQoCggEBAME0HKmIzfTOwkKLT3THHe+ObdizamPg"
		"UZmD64Tf3zJdNeYGYn4CEXbyP6fy3tWc8S2boW6dzrH8SdFf9uo320GJA9B7U1FW"
		"Te3xda/Lm3JFfaHjkWw7jBwcauQZjpGINHapHRlpiCZsquAthOgxW9SgDgYlGzEA"
		"s06pkEFiMw+qDfLo/sxFKB6vQlFekMeCymjLCbNwPJyqyhFmPWwio/PDMruBTzPH"
		"3cioBnrJWKXc3OjXdLGFJOfj7pP0j/dr2LH72eSvv3PQQFl90CZPFhrCUcRHSSxo"
		"E6yjGOdnz7f6PveLIB574kQORwt8ePn0yidrTC1ictikED3nHYhMUOUCAwEAAaNT"
		"MFEwHQYDVR0OBBYEFPVV6xBUFPiGKDyo5V3+Hbh4N9YSMB8GA1UdIwQYMBaAFPVV"
		"6xBUFPiGKDyo5V3+Hbh4N9YSMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL"
		"BQADggEBAGa9kS21N70ThM6/Hj9D7mbVxKLBjVWe2TPsGfbl3rEDfZ+OKRZ2j6AC"
		"6r7jb4TZO3dzF2p6dgbrlU71Y/4K0TdzIjRj3cQ3KSm41JvUQ0hZ/c04iGDg/xWf"
		"+pp58nfPAYwuerruPNWmlStWAXf0UTqRtg4hQDWBuUFDJTuWuuBvEXudz74eh/wK"
		"sMwfu1HFvjy5Z0iMDU8PUDepjVolOCue9ashlS4EB5IECdSR2TItnAIiIwimx839"
		"LdUdRudafMu5T5Xma182OC0/u/xRlEm+tvKGGmfFcN0piqVl8OrSPBgIlb+1IKJE"
		"m/XriWr/Cq4h/JfB7NTsezVslgkBaoU="
		"\"}"
	  "],"
	  "\"trust_stores\": [" /* named cert chains */
		"{"
			"\"name\": \"mosq_org\","
			"\"stack\": ["
				"\"test_mosq_org\""
			"]"
		"}"
	  "],"
	  "\"s\": [" /* the supported stream types */
		"{\"mosq_nontls\": {"
			"\"endpoint\":"		"\"test.mosquitto.org\","
			"\"port\":"		"1883,"
			"\"protocol\":"		"\"mqtt\","
			"\"mqtt_topic\":"	"\"test/topic1\","
			"\"mqtt_subscribe\":"	"\"test/topic1\","
			"\"mqtt_qos\":"         "0,"
			"\"retry\":"            "\"default\","
	        	"\"mqtt_keep_alive\":"  "60,"
			"\"mqtt_clean_start\":" "true,"
			"\"mqtt_will_topic\":"  "\"good/bye\","
			"\"mqtt_will_message\":" "\"sign-off\","
			"\"mqtt_will_qos\":"    "0,"
			"\"mqtt_will_retain\":" "0,"
			"\"aws_iot\":" "false"
		"}},"
		"{\"mosq_tls\": {"
			"\"endpoint\":"		"\"test.mosquitto.org\","
			"\"port\":"		"8884,"
			"\"tls\":"              "true,"
			"\"client_cert\":"      "0,"
			"\"tls_trust_store\":"  "\"mosq_org\","
			"\"protocol\":"		"\"mqtt\","
			"\"mqtt_topic\":"	"\"test/topic1\","
			"\"mqtt_subscribe\":"	"\"test/topic1\","
			"\"mqtt_qos\":"         "0,"
			"\"retry\":"            "\"default\","
	        	"\"mqtt_keep_alive\":"  "60,"
			"\"mqtt_clean_start\":" "true,"
			"\"mqtt_will_topic\":"  "\"good/bye\","
			"\"mqtt_will_message\":" "\"sign-off\","
			"\"mqtt_will_qos\":"    "0,"
			"\"mqtt_will_retain\":" "0,"
			"\"aws_iot\":" "false"
		"}}"

		"]"
	"}"
;
#endif

typedef struct myss {
	struct lws_ss_handle 	*ss;
	void			*opaque_data;
	/* ... application specific state ... */
	lws_sorted_usec_list_t sul;
	size_t size;
	int tx_count;
} myss_t;

static const uint8_t client_key[] = {
	0x30, 0x82, 0x04, 0xa2, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,
	0xc0, 0xab, 0xd4, 0x5c, 0x16, 0x7f, 0x30, 0x86, 0x99, 0x20, 0xab, 0xbd,
	0xdf, 0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xb5, 0x04, 0x01, 0x26, 0x2a, 0xba, 0xa9, 0xec, 0x19, 0xa0,
	0x27, 0x1a, 0x7d, 0x03, 0xe3, 0x77, 0x0f, 0x86, 0xed, 0x89, 0xfc, 0x88,
	0x38, 0x68, 0x0b, 0x05, 0x47, 0xa0, 0xf8, 0x8a, 0x95, 0x1a, 0x05, 0x48,
	0x23, 0x71, 0xb9, 0xf8, 0x1d, 0x18, 0x55, 0x7c, 0x01, 0x8f, 0x3a, 0xb9,
	0x52, 0xee, 0xc8, 0x87, 0x93, 0x3c, 0x6d, 0x49, 0x01, 0xab, 0xc0, 0xda,
	0x35, 0xd4, 0x7e, 0x72, 0xd8, 0x2e, 0xb3, 0xe8, 0xaf, 0x89, 0xb6, 0x4d,
	0xce, 0x4c,
};

static const uint8_t client_cert_der[] = {
	0x30, 0x82, 0x03, 0x88, 0x30, 0x82, 0x02, 0x70, 0xa0, 0x03, 0x02, 0x01,
	0x02, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
	0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x81, 0x90, 0x31, 0x0b,
	0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47, 0x42, 0x31,
	0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0e, 0x55, 0x6e,
	0x69, 0x74, 0x65, 0x64, 0x20, 0x4b, 0x69, 0x6e, 0x67, 0x64, 0x6f, 0x6d,
	0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x44,
	0x65, 0x72, 0x62, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04,
	0x0a, 0x0c, 0x09, 0x4d, 0x6f, 0x73, 0x71, 0x75, 0x69, 0x74, 0x74, 0x6f,
	0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x43,
	0x41, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0d,
	0x6d, 0x6f, 0x73, 0x71, 0x75, 0x69, 0x74, 0x74, 0x6f, 0x2e, 0x6f, 0x72,
	0x67, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
	0x0d, 0x01, 0x09, 0x01, 0x16, 0x10, 0x72, 0x6f, 0x67, 0x65, 0x72, 0x40,
	0x61, 0x74, 0x63, 0x68, 0x6f, 0x6f, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x1e,
	0x17, 0x0d, 0x32, 0x32, 0x30, 0x32, 0x30, 0x33, 0x31, 0x37, 0x31, 0x31,
	0x34, 0x37, 0x5a, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x35, 0x30, 0x34, 0x31,
	0x37, 0x31, 0x31, 0x34, 0x37, 0x5a, 0x30, 0x62, 0x31, 0x0b, 0x30, 0x09,
	0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30,
	0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x43, 0x61, 0x6c, 0x69,
	0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03,
	0x55, 0x04, 0x07, 0x0c, 0x09, 0x53, 0x75, 0x6e, 0x6e, 0x79, 0x76, 0x61,
	0x6c, 0x65, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
	0x03, 0x4c, 0x57, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04,
	0x0b, 0x0c, 0x02, 0x53, 0x53, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55,
	0x04, 0x03, 0x0c, 0x06, 0x53, 0x53, 0x4d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x3c, 0xf8, 0x74, 0x6f, 0x64, 0x78, 0xd0, 0x28, 0x65, 0x90,
	0x8e, 0x42, 0xb8, 0xca, 0x53, 0x45, 0x8a, 0x9c, 0x11, 0xe2, 0x3b, 0xb6,
	0x6e, 0xa3, 0x2d, 0x4c, 0x23, 0x55, 0xa2, 0xa5, 0x02, 0xc3, 0x59, 0xf6,
	0x15, 0xaf, 0x8f, 0x13, 0x9e, 0x6e, 0xa1, 0x84, 0x29, 0x2d, 0x0e, 0xcc,
	0xed, 0x6c, 0x51, 0xf7, 0x2b, 0xf4, 0x10, 0x99,
};

static void sul_cb(lws_sorted_usec_list_t* sul) {
	myss_t* m = (myss_t*)lws_container_of(sul, myss_t, sul);
	lws_ss_state_return_t ret;

	ret = lws_ss_request_tx(m->ss);
        if (ret != LWSSSSRET_OK || interrupted) {
            return;
        }

	lws_sul_schedule(lws_ss_get_context(m->ss), 0, &m->sul, sul_cb,
			 3 * LWS_USEC_PER_SEC);
}

/* secure streams payload interface */

static lws_ss_state_return_t
myss_rx(void *userobj, const uint8_t *buf, size_t len, int flags) {
	lwsl_user("%s: len %d, flags: %d\n", __func__, (int)len, flags);
	lwsl_hexdump_info(buf, len);

	if (flags & LWSSS_FLAG_EOM) {
		bad = 0;
		interrupted = 1;
	}

	return LWSSSSRET_OK;
}

static lws_ss_state_return_t
myss_tx(void *userobj, lws_ss_tx_ordinal_t ord, uint8_t *buf, size_t *len,
	int *flags) {
	myss_t* m = (myss_t*)userobj;
	size_t os = m->size;
	*flags = 0;

	if (!m->size) {
		lwsl_user("Start of message\n");
 		*flags |= LWSSS_FLAG_SOM;
	}

	*len = (size_t) lws_snprintf((char*)buf, *len, "{\"unixtime\":%lu}",
				     (unsigned long)lws_now_secs());
	*flags |= LWSSS_FLAG_EOM;
	m->size = 0;

	lwsl_user("%s: h: %p, [%d]sending %u - %u flags 0x%x\n", __func__, m->ss,
		  m->tx_count, (unsigned int)os, (unsigned int)(os + *len),
		  *flags);

	return LWSSSSRET_OK;
}

static lws_ss_state_return_t
myss_state(void *userobj, void *sh, lws_ss_constate_t state,
		lws_ss_tx_ordinal_t ack) {
	myss_t *m = (myss_t *)userobj;

	lwsl_user("%s: %s, ord 0x%x\n", __func__, lws_ss_state_name((int)state),
		  (unsigned int)ack);

	switch (state) {
	case LWSSSCS_CREATING:
		return lws_ss_request_tx(m->ss);
	case LWSSSCS_CONNECTED:
		lws_sul_schedule(lws_ss_get_context(m->ss), 0, &m->sul, sul_cb,
 				 1 * LWS_USEC_PER_SEC);
		break;
	case LWSSSCS_DESTROYING:
		lws_sul_schedule(lws_ss_get_context(m->ss), 0, &m->sul, sul_cb,
 				 LWS_SET_TIMER_USEC_CANCEL);
		break;

	case LWSSSCS_ALL_RETRIES_FAILED:
		/* if we're out of retries, we want to close the app and FAIL */
		interrupted = 1;
		break;
	default:
		break;
	}

	return 0;
}

static int
app_system_state_nf(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
		    int current, int target)
{
	struct lws_context *context = lws_system_context_from_system_mgr(mgr);
	/*
	 * For the things we care about, let's notice if we are trying to get
	 * past them when we haven't solved them yet, and make the system
	 * state wait while we trigger the dependent action.
	 */
	switch (target) {

#if !defined(LWS_SS_USE_SSPC)

	/*
	 * The proxy takes responsibility for this stuff if we get things
	 * done through that
	 */

	case LWS_SYSTATE_INITIALIZED: /* overlay on the hardcoded policy */
	case LWS_SYSTATE_POLICY_VALID: /* overlay on the loaded policy */

		if (target != current)
			break;

	case LWS_SYSTATE_REGISTERED:
		break;
#endif

	case LWS_SYSTATE_OPERATIONAL:
		if (current == LWS_SYSTATE_OPERATIONAL) {
			lws_ss_info_t ssi;

			/* We're making an outgoing secure stream ourselves */

			memset(&ssi, 0, sizeof(ssi));
			ssi.handle_offset = offsetof(myss_t, ss);
			ssi.opaque_user_data_offset = offsetof(myss_t,
							       opaque_data);
			ssi.rx = myss_rx;
			ssi.tx = myss_tx;
			ssi.state = myss_state;
			ssi.user_alloc = sizeof(myss_t);
			ssi.streamtype = test_nontls ? "mosq_nontls" : "mosq_tls";

			if (lws_ss_create(context, 0, &ssi, NULL, NULL,
					  NULL, NULL)) {
				lwsl_err("%s: failed to create secure stream\n",
					 __func__);
				interrupted = 1;
				lws_cancel_service(context);
				return -1;
			}
		}
		break;
	}

	return 0;
}

static lws_state_notify_link_t * const app_notifier_list[] = {
	&nl, NULL
};

static void
sigint_handler(int sig)
{
	interrupted = 1;
}

int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	int n = 0, expected = 0;
	const char *p;

	signal(SIGINT, sigint_handler);

	memset(&info, 0, sizeof info);
	lws_cmdline_option_handle_builtin(argc, argv, &info);

	lwsl_user("LWS secure streams mqtt test client [-d<verb>]\n");

	/* these options are mutually exclusive if given */
	if (lws_cmdline_option(argc, argv, "--nontls"))
		test_nontls = 1;

	info.fd_limit_per_thread = 1 + 6 + 1;
	info.port = CONTEXT_PORT_NO_LISTEN;
#if defined(LWS_SS_USE_SSPC)
	info.protocols = lws_sspc_protocols;
#else
	info.pss_policies_json = default_ss_policy;
	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
		       LWS_SERVER_OPTION_H2_JUST_FIX_WINDOW_UPDATE_OVERFLOW |
		       LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
#endif

	/* integrate us with lws system state management when context created */
	nl.name = "app";
	nl.notify_cb = app_system_state_nf;
	info.register_notifier_list = app_notifier_list;

	/* create the context */
	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		goto bail;
	}

	/*
	 * Set the related lws_system blobs
	 *
	 * ...direct_set() sets a pointer, so the thing pointed to has to have
	 * a suitable lifetime, eg, something that already exists on the heap or
	 * a const string in .rodata like this
	 */

	lws_system_blob_direct_set(
			lws_system_get_blob(context, LWS_SYSBLOB_TYPE_MQTT_CLIENT_ID, 0),
			(const uint8_t*)TEST_CLIENT_ID, strlen(TEST_CLIENT_ID));

	lws_system_blob_direct_set(
			lws_system_get_blob(context, LWS_SYSBLOB_TYPE_CLIENT_CERT_DER, 0),
			client_cert_der, sizeof(client_cert_der));

	lws_system_blob_direct_set(
			lws_system_get_blob(context, LWS_SYSBLOB_TYPE_CLIENT_KEY_DER, 0),
			client_key, sizeof(client_key));

	/* the event loop */
	while (n >= 0 && !interrupted)
		n = lws_service(context, 0);

	lws_context_destroy(context);

bail:
	if ((p = lws_cmdline_option(argc, argv, "--expected-exit")))
		expected = atoi(p);

	if (bad == expected) {
		lwsl_user("Completed: OK (seen expected %d)\n", expected);
		return 0;
	} else
		lwsl_err("Completed: failed: exit %d, expected %d\n", bad, expected);

	return 1;
}
